package org.jackysoft.service.impl;

import java.io.File;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.jackysoft.entity.OfficeDocument;
import org.jackysoft.query.Query;
import org.jackysoft.service.AbstractIdentifiedService;
import org.jackysoft.service.AbstractStringIdServiceImpl;
import org.jackysoft.service.OfficeDocumentService;
import org.jackysoft.util.Office2PDF;
import org.jackysoft.util.Page;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class OfficeDocumentServiceImpl extends
AbstractStringIdServiceImpl<OfficeDocument> implements
		OfficeDocumentService {

	/**
	 * 
	 */
	private static final long serialVersionUID = 8403149518031262688L;

	public OfficeDocumentServiceImpl() {
		this.type = OfficeDocument.class;
	}

	/**
	 * 调用系统打印机把word转换成PDF
	 * 
	 * @throws ExecutionException
	 * @throws InterruptedException
	 * */
	@Override
	public String printToPDF(OfficeDocument office)
			throws InterruptedException, ExecutionException {
		String pdfDir = getConfig().getPdfPath();
		ExecutorService executor = Executors.newSingleThreadExecutor();
		Office2PDF wpf = new Office2PDF(getConfig().getPdfServer(),
				getConfig().getPdfServerPort(), office.getExt(),
				office.getCollateData());
		Future<String> future = executor.submit(wpf);
		String name = future.get();
		executor.shutdown();
		return pdfDir + File.separator + name + ".pdf";
	}

	@Override
	public boolean exists(long mills) {
		String hql = "from  " + this.entitytable()
				+ " o where o.dateTimeStamp=:dts";
		boolean bl = getSession().createQuery(hql).setLong("dts", mills).list()
				.isEmpty();
		return !bl;
	}

	@Override
	public void remove(long mills) {
		String hql = "delete from  " + this.entitytable()
				+ " o where o.dateTimeStamp=:dts";
		int rl = getSession().createQuery(hql).setLong("dts", mills).executeUpdate();
		getSession().flush();
        
	}

	@Override
	public OfficeDocument getByMills(long mills) {
		String hql = "from  " + this.entitytable()
				+ " o where o.dateTimeStamp=:dts";
		List list = getSession().createQuery(hql).setLong("dts", mills).list();
		return (OfficeDocument) (list.isEmpty() ? null : list.get(0));
	}

	@Override
	public Page query(Query qc, Integer pindex, Integer rows)
			throws DataAccessException {
		
		return super.query(qc, pindex, rows);
	}

	@Override
	public int count(Query qc) throws DataAccessException {
	
		return super.count(qc);
	}
	
	

}